<template>
  <div class="employee-schedule">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>我的排班</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <el-form :model="filterForm" inline>
          <el-form-item label="查看月份">
            <el-date-picker
              v-model="filterForm.month"
              type="month"
              placeholder="请选择月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="状态筛选">
            <el-select
              v-model="filterForm.status"
              placeholder="全部状态"
              clearable
              style="width: 120px"
            >
              <el-option label="已确认" value="CONFIRMED" />
              <el-option label="待确认" value="PENDING" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="handleResetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ scheduleStats.totalDays }}</div>
                <div class="stat-label">本月工作天数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ scheduleStats.totalHours }}</div>
                <div class="stat-label">本月工作小时</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ scheduleStats.overtimeHours }}</div>
                <div class="stat-label">本月加班小时</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">¥{{ scheduleStats.estimatedSalary }}</div>
                <div class="stat-label">预估工资</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 日历视图 -->
    <div class="calendar-section">
      <el-card header="排班日历" class="calendar-card">
        <div class="calendar-toolbar">
          <div class="calendar-nav">
            <el-button @click="handlePrevMonth">
              <el-icon><ArrowLeft /></el-icon>
              上月
            </el-button>
            <span class="current-month">{{ currentMonthText }}</span>
            <el-button @click="handleNextMonth">
              下月
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          <div class="view-toggle">
            <el-radio-group v-model="viewMode">
              <el-radio-button label="calendar">日历视图</el-radio-button>
              <el-radio-button label="list">列表视图</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 日历视图 -->
        <div v-if="viewMode === 'calendar'" class="calendar-view">
          <el-calendar v-model="calendarDate" class="schedule-calendar">
            <template #date-cell="{ data }">
              <div class="calendar-cell">
                <div class="cell-date">{{ data.day.split('-').slice(-1)[0] }}</div>
                <div v-if="getScheduleForDate(data.day)" class="cell-schedule">
                  <div
                    v-for="schedule in getScheduleForDate(data.day)"
                    :key="schedule.id"
                    :class="['schedule-item', getScheduleStatusClass(schedule.status)]"
                    @click="handleViewScheduleDetail(schedule)"
                  >
                    <div class="schedule-time">
                      {{ schedule.startTime }} - {{ schedule.endTime }}
                    </div>
                    <div class="schedule-room">{{ schedule.roomNumber }}</div>
                  </div>
                </div>
              </div>
            </template>
          </el-calendar>
        </div>

        <!-- 列表视图 -->
        <div v-if="viewMode === 'list'" class="list-view">
          <el-table
            v-loading="loading"
            :data="scheduleList"
            stripe
            border
          >
            <el-table-column prop="date" label="日期" width="120">
              <template #default="{ row }">
                {{ formatDate(row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="100" />
            <el-table-column prop="endTime" label="结束时间" width="100" />
            <el-table-column prop="roomNumber" label="房间" width="100" />
            <el-table-column prop="customerName" label="客户" width="120" />
            <el-table-column prop="workHours" label="工作时长" width="100">
              <template #default="{ row }">
                {{ row.workHours }}小时
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getScheduleStatusTagType(row.status)">
                  {{ getScheduleStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" min-width="150" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleViewScheduleDetail(row)">
                  详情
                </el-button>
                <el-button
                  v-if="row.status === 'PENDING'"
                  type="success"
                  size="small"
                  @click="handleConfirmSchedule(row)"
                >
                  确认
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 排班详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="排班详情"
      width="600px"
    >
      <div v-if="selectedSchedule" class="schedule-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日期">
            {{ formatDate(selectedSchedule.date) }}
          </el-descriptions-item>
          <el-descriptions-item label="时间">
            {{ selectedSchedule.startTime }} - {{ selectedSchedule.endTime }}
          </el-descriptions-item>
          <el-descriptions-item label="房间">
            {{ selectedSchedule.roomNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="客户">
            {{ selectedSchedule.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="工作时长">
            {{ selectedSchedule.workHours }}小时
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getScheduleStatusTagType(selectedSchedule.status)">
              {{ getScheduleStatusText(selectedSchedule.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(selectedSchedule.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedSchedule.remarks || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            v-if="selectedSchedule && selectedSchedule.status === 'PENDING'"
            type="success"
            @click="handleConfirmSchedule(selectedSchedule)"
          >
            确认排班
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Calendar,
  Clock,
  Timer,
  Money,
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue'
import {
  getEmployeeScheduleView,
  updateSchedule
} from '@/api/schedule'

// 响应式数据
const loading = ref(false)
const viewMode = ref('calendar')
const calendarDate = ref(new Date())
const scheduleList = ref([])
const scheduleStats = ref({
  totalDays: 0,
  totalHours: 0,
  overtimeHours: 0,
  estimatedSalary: 0
})
const detailDialogVisible = ref(false)
const selectedSchedule = ref(null)

// 筛选表单
const filterForm = reactive({
  month: new Date().toISOString().slice(0, 7),
  status: null
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 当前月份文本
const currentMonthText = computed(() => {
  const date = new Date(calendarDate.value)
  return `${date.getFullYear()}年${date.getMonth() + 1}月`
})

// 获取员工排班数据
const fetchEmployeeSchedule = async () => {
  loading.value = true
  try {
    const params = {
      month: filterForm.month,
      status: filterForm.status,
      page: pagination.page - 1,
      size: pagination.size
    }

    const response = await getEmployeeScheduleView(params)
    const data = response.data
    
    scheduleList.value = data.schedules || []
    scheduleStats.value = data.statistics || scheduleStats.value
    pagination.total = data.totalElements || 0
  } catch (error) {
    ElMessage.error('获取排班信息失败')
  } finally {
    loading.value = false
  }
}

// 获取指定日期的排班
const getScheduleForDate = (date) => {
  return scheduleList.value.filter(schedule => schedule.date === date)
}

// 处理筛选
const handleFilter = () => {
  pagination.page = 1
  fetchEmployeeSchedule()
}

// 重置筛选
const handleResetFilter = () => {
  Object.assign(filterForm, {
    month: new Date().toISOString().slice(0, 7),
    status: null
  })
  pagination.page = 1
  fetchEmployeeSchedule()
}

// 刷新数据
const handleRefresh = () => {
  fetchEmployeeSchedule()
}

// 上一月
const handlePrevMonth = () => {
  const date = new Date(calendarDate.value)
  date.setMonth(date.getMonth() - 1)
  calendarDate.value = date
  filterForm.month = date.toISOString().slice(0, 7)
  fetchEmployeeSchedule()
}

// 下一月
const handleNextMonth = () => {
  const date = new Date(calendarDate.value)
  date.setMonth(date.getMonth() + 1)
  calendarDate.value = date
  filterForm.month = date.toISOString().slice(0, 7)
  fetchEmployeeSchedule()
}

// 查看排班详情
const handleViewScheduleDetail = (schedule) => {
  selectedSchedule.value = schedule
  detailDialogVisible.value = true
}

// 确认排班
const handleConfirmSchedule = async (schedule) => {
  try {
    await ElMessageBox.confirm(
      '确定要确认这个排班吗？',
      '确认排班',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    await updateSchedule(schedule.id, {
      ...schedule,
      status: 'CONFIRMED'
    })

    ElMessage.success('排班确认成功')
    detailDialogVisible.value = false
    fetchEmployeeSchedule()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认排班失败')
    }
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchEmployeeSchedule()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchEmployeeSchedule()
}

// 获取排班状态样式类
const getScheduleStatusClass = (status) => {
  const classMap = {
    CONFIRMED: 'status-confirmed',
    PENDING: 'status-pending',
    CANCELLED: 'status-cancelled'
  }
  return classMap[status] || 'status-pending'
}

// 获取排班状态标签类型
const getScheduleStatusTagType = (status) => {
  const typeMap = {
    CONFIRMED: 'success',
    PENDING: 'warning',
    CANCELLED: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取排班状态文本
const getScheduleStatusText = (status) => {
  const textMap = {
    CONFIRMED: '已确认',
    PENDING: '待确认',
    CANCELLED: '已取消'
  }
  return textMap[status] || status
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEmployeeSchedule()
})
</script>

<style scoped>
.employee-schedule {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 15px;
}

.stat-icon {
  font-size: 32px;
  color: #409eff;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.calendar-section {
  margin-bottom: 20px;
}

.calendar-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.calendar-card :deep(.el-card__header) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.calendar-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.calendar-nav {
  display: flex;
  align-items: center;
  gap: 15px;
}

.current-month {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.schedule-calendar :deep(.el-calendar-table .el-calendar-day) {
  height: 100px;
  padding: 5px;
}

.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.cell-date {
  font-weight: 600;
  margin-bottom: 5px;
}

.cell-schedule {
  flex: 1;
  overflow: hidden;
}

.schedule-item {
  font-size: 12px;
  padding: 2px 4px;
  margin-bottom: 2px;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.3s;
}

.schedule-item:hover {
  transform: scale(1.05);
}

.status-confirmed {
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
  color: #67c23a;
}

.status-pending {
  background-color: #fdf6ec;
  border: 1px solid #e6a23c;
  color: #e6a23c;
}

.status-cancelled {
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
  color: #f56c6c;
}

.schedule-time {
  font-weight: 600;
}

.schedule-room {
  font-size: 11px;
  opacity: 0.8;
}

.list-view {
  min-height: 400px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.schedule-detail {
  padding: 10px 0;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>